<?php

// +----------------------------------------------------------------------
// | Ht.Shop
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
error_reporting(E_ERROR | E_WARNING | E_PARSE);

define('CHARSET','UTF-8');

// 基本常量定义
define('MD5_KEY', md5(sysconf('md5_key'))); // md5 加密key

define('ATTACH_STORE','client/store');

define('BASE_ROOT_PATH',str_replace('\\','/',dirname(dirname(__FILE__))));//E:/wamp/www/ht-shop
define("BASE_UPLOAD_PATH", BASE_ROOT_PATH . "/static/upload");//原 data/upload


define('UPLOAD_SITE_URL',get_root_url().'/static/upload');

define('TIMESTAMP',time());

/**
 *  订单状态
 */
//已取消
define('ORDER_STATE_CANCEL', 0);
//已产生但未支付
define('ORDER_STATE_NEW', 10);
//已支付
define('ORDER_STATE_PAY', 20);
//已发货
define('ORDER_STATE_SEND', 30);
//已收货，交易成功
define('ORDER_STATE_SUCCESS', 40);
//订单超过N小时未支付自动取消
define('ORDER_AUTO_CANCEL_TIME', 1);
//订单超过N天未收货自动收货
define('ORDER_AUTO_RECEIVE_DAY', 10);


//订单分类-餐饮1
define('ORDER_CLASS_CANYIN', 1);
//订单分类-酒店2
define('ORDER_CLASS_JIUDIAN', 2);
//订单分类-特产
define('ORDER_CLASS_TECHAN', 3);


//预订尾款支付期限(小时)
define('BOOK_AUTO_END_TIME', 72);

//门店支付订单支付提货期限(天)
define('CHAIN_ORDER_PAYPUT_DAY', 7);
/**
 * 订单删除状态
 */
//默认未删除
define('ORDER_DEL_STATE_DEFAULT', 0);
//已删除
define('ORDER_DEL_STATE_DELETE', 1);
//彻底删除
define('ORDER_DEL_STATE_DROP', 2);

define('ATTACH_PATH','shop');

use think\Db;

/**
 * 读取缓存信息
 *
 * @param string $key 要取得缓存键
 * @param string $prefix 键值前缀
 * @param string $fields 所需要的字段
 * @return array/bool
 */
function rcache($key = null, $prefix = '', $fields = '*'){
    if ($key===null || !config('cache_open')) return array();
//    $ins = Cache::getInstance('cacheredis');
//    $cache_info = $ins->hget($key,$prefix,$fields);

    $ins = new \think\Cache();
    $cache_info = $ins->get($key,$prefix,$fields);
    if ($cache_info === false) {
        //取单个字段且未被缓存
        $data  = array();
    } elseif (is_array($cache_info)) {
        //如果有一个键值为false(即未缓存)，则整个函数返回空，让系统重新生成全部缓存
        $data = $cache_info;
        foreach ($cache_info as $k => $v) {
            if ($v === false) {
                $data = array();break;
            }
        }
    } else {
        //string 取单个字段且被缓存
        $data = array($fields => $cache_info);
    }
    // 验证缓存是否过期
    if (isset($data['cache_expiration_time']) && $data['cache_expiration_time'] < TIMESTAMP) {
        $data = array();
    }
    return $data;
}

/**
 * 写入缓存
 *
 * @param string $key 缓存键值
 * @param array $data 缓存数据
 * @param string $prefix 键值前缀
 * @param int $period 缓存周期  单位分，0为永久缓存
 * @return bool 返回值
 */
function wcache($key = null, $data = array(), $prefix, $period = 0){
    if ($key===null || !config('cache_open') || !is_array($data)) return;
    $period = intval($period);
    if ($period != 0) {
        $data['cache_expiration_time'] = time() + $period * 60;
    }
    $ins = Cache::getInstance('cacheredis');
    $ins->hset($key, $prefix, $data);
    $cache_info = $ins->hget($key,$prefix);
    return true;
}

/**
 * 删除缓存
 * @param string $key 缓存键值
 * @param string $prefix 键值前缀
 * @return boolean
 */
function dcache($key = null, $prefix = ''){
    if ($key===null || !config('cache_open')) return true;

    $ins = Cache::getInstance('cacheredis');
    return $ins->hdel($key, $prefix);
}



/**
 * 加密函数
 *
 * @param string $txt 需要加密的字符串
 * @param string $key 密钥
 * @return string 返回加密结果
 */
if (!function_exists("encrypt")) {

    function encrypt($txt, $key = ''){
        if (empty($txt)) return $txt;
        if (empty($key)) $key = md5(MD5_KEY);
        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
        $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
        $nh1 = rand(0,64);
        $nh2 = rand(0,64);
        $nh3 = rand(0,64);
        $ch1 = $chars{$nh1};
        $ch2 = $chars{$nh2};
        $ch3 = $chars{$nh3};
        $nhnum = $nh1 + $nh2 + $nh3;
        $knum = 0;$i = 0;
        while(isset($key{$i})) $knum +=ord($key{$i++});
        $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum%8,$knum%8 + 16);
        $txt = base64_encode(time().'_'.$txt);
        $txt = str_replace(array('+','/','='),array('-','_','.'),$txt);
        $tmp = '';
        $j=0;$k = 0;
        $tlen = strlen($txt);
        $klen = strlen($mdKey);
        for ($i=0; $i<$tlen; $i++) {
            $k = $k == $klen ? 0 : $k;
            $j = ($nhnum+strpos($chars,$txt{$i})+ord($mdKey{$k++}))%64;
            $tmp .= $chars{$j};
        }
        $tmplen = strlen($tmp);
        $tmp = substr_replace($tmp,$ch3,$nh2 % ++$tmplen,0);
        $tmp = substr_replace($tmp,$ch2,$nh1 % ++$tmplen,0);
        $tmp = substr_replace($tmp,$ch1,$knum % ++$tmplen,0);
        return $tmp;
    }

}


/**
 * 解密函数
 *
 * @param string $txt 需要解密的字符串
 * @param string $key 密匙
 * @return string 字符串类型的返回结果
 */
if (!function_exists("decrypt")) {

    function decrypt($txt, $key = '', $ttl = 0){
        if (empty($txt)) return $txt;
        if (empty($key)) $key = md5(MD5_KEY);

        $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.";
        $ikey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm";
        $knum = 0;$i = 0;
        $tlen = @strlen($txt);
        while(isset($key{$i})) $knum +=ord($key{$i++});
        $ch1 = @$txt{$knum % $tlen};
        $nh1 = strpos($chars,$ch1);
        $txt = @substr_replace($txt,'',$knum % $tlen--,1);
        $ch2 = @$txt{$nh1 % $tlen};
        $nh2 = @strpos($chars,$ch2);
        $txt = @substr_replace($txt,'',$nh1 % $tlen--,1);
        $ch3 = @$txt{$nh2 % $tlen};
        $nh3 = @strpos($chars,$ch3);
        $txt = @substr_replace($txt,'',$nh2 % $tlen--,1);
        $nhnum = $nh1 + $nh2 + $nh3;
        $mdKey = substr(md5(md5(md5($key.$ch1).$ch2.$ikey).$ch3),$nhnum % 8,$knum % 8 + 16);
        $tmp = '';
        $j=0; $k = 0;
        $tlen = @strlen($txt);
        $klen = @strlen($mdKey);
        for ($i=0; $i<$tlen; $i++) {
            $k = $k == $klen ? 0 : $k;
            $j = strpos($chars,$txt{$i})-$nhnum - ord($mdKey{$k++});
            while ($j<0) $j+=64;
            $tmp .= $chars{$j};
        }
        $tmp = str_replace(array('-','_','.'),array('+','/','='),$tmp);
        $tmp = trim(base64_decode($tmp));

        if (preg_match("/\d{10}_/s",substr($tmp,0,11))){
            if ($ttl > 0 && (time() - substr($tmp,0,11) > $ttl)){
                $tmp = null;
            }else{
                $tmp = substr($tmp,11);
            }
        }
        return $tmp;
    }

}


/**
 * 设置cookie
 *
 * @param string $name cookie 的名称
 * @param string $value cookie 的值
 * @param string $expire cookie 有效周期
 * @param string $path cookie 的服务器路径 默认为 /
 * @param string $domain cookie 的域名
 * @param bool $secure 是否通过安全的 HTTPS 连接来传输 cookie,默认为false
 */
function setHtCookie($name, $value, $expire = '3600', $path = '', $domain = '', $secure = false){
    if (empty($path)) {
        $path = '/';
    }
    if (empty($domain)) {
        $domain = '';
    }
    $expire = intval($expire) ? intval($expire) : 3600;
    setcookie($name, $value, time() + $expire, $path, $domain, $secure);
    $_COOKIE[$name] = $value;
}

/**
 * 20171011 kevin
 * 取得IP
 * @return string 字符串类型的返回结果
 */
function getIp(){
    if (@$_SERVER['HTTP_CLIENT_IP'] && $_SERVER['HTTP_CLIENT_IP']!='unknown') {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (@$_SERVER['HTTP_X_FORWARDED_FOR'] && $_SERVER['HTTP_X_FORWARDED_FOR']!='unknown') {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return preg_match('/^\d[\d.]+\d$/', $ip) ? $ip : '';
}




/**
* 取得订单状态文字输出形式
*
* @param array $order_info 订单数组
* @return string $order_state 描述输出
*/
function orderState($order_info) {
    switch ($order_info['order_state']) {
        case ORDER_STATE_CANCEL://0
            $order_state = '已取消';
        break;
        case ORDER_STATE_NEW://10
            if ($order_info['chain_code']) {
                $order_state = '门店付款自提';
            } else {
                $order_state = '待付款';
            }
        break;
        case ORDER_STATE_PAY://20
            if ($order_info['chain_code']) {
                $order_state = '待自提';
            } elseif($order_info['order_class']==1 || $order_info['order_class']==2){//酒店或者餐饮就支付完成 20就显示待消费状态
            	$order_state = '待消费';
            } else {
                $order_state = '待发货';
            }
        break;
        case ORDER_STATE_SEND://30
            $order_state = '待收货';
        break;
        case ORDER_STATE_SUCCESS://40
            $order_state = '交易完成';
        break;
    }
    return $order_state;
}


/**
 * 取得订单支付类型文字输出形式
 *
 * @param array $payment_code
 * @return string
 */
function orderPaymentName($payment_code) {
    return str_replace(
            array('offline','online','ali_native','alipay','tenpay','chinabank','predeposit','wxpay','wx_jsapi','wx_saoma','chain'),
            array('货到付款','在线付款','支付宝移动支付','支付宝','财付通','网银在线','站内余额支付','微信支付[客户端]','微信支付[jsapi]','微信支付[扫码]','门店支付'),
            $payment_code);
}


function request_uri()
{
    if (isset($_SERVER['REQUEST_URI']))
    {
        $uri = $_SERVER['REQUEST_URI'];
    }
    else
    {
        if (isset($_SERVER['argv']))
        {
            $uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['argv'][0];
        }
        else
        {
            $uri = $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
        }
    }
    return $uri;
}

/**
 * 取得订单商品销售类型文字输出形式
 *
 * @param array $goods_type
 * @return string 描述输出
 */
function orderGoodsType($goods_type) {
    return str_replace(array(
        '1','2','3','4','5',
        '8', '9',
    ), array(
        '','抢购','限时折扣','优惠套装','赠品',
        '', '换购',
    ), $goods_type);
}

/**
 * 20171206 kevin
* 价格格式化
*
* @param int	$price
* @return string	$price_format
*/
function ncPriceFormat($price) {
    return number_format($price,2,'.','');
}



/**
 * 消息提示，主要适用于普通页面AJAX提交的情况
 *
 * @param string $message 消息内容
 * @param string $url 提示完后的URL去向
 * @param stting $alert_type 提示类型 error/succ/notice 分别为错误/成功/警示
 * @param string $extrajs 扩展JS
 * @param int $time 停留时间
 */
function showDialog($message = '', $url = '', $alert_type = 'error', $extrajs = '', $time = 2){
	$get=input('get.');
	if (empty($get['inajax'])){
		if ($url == 'reload') $url = '';
		showMessage($message.$extrajs,$url,'html',$alert_type,1,$time*1000);
	}
	$message = str_replace("'", "\\'", strip_tags($message));

	$paramjs = null;
	if ($url == 'reload'){
		$paramjs = 'window.location.reload()';
	}elseif ($url != ''){
		$paramjs = 'window.location.href =\''.$url.'\'';
	}
	if ($paramjs){
		$paramjs = 'function (){'.$paramjs.'}';
	}else{
		$paramjs = 'null';
	}
	$modes = array('error' => 'alert', 'succ' => 'succ', 'notice' => 'notice','js'=>'js');
	$cover = $alert_type == 'error' ? 1 : 0;
	$extra='';
	$extra .= 'showDialog(\''.$message.'\', \''.$modes[$alert_type].'\', null, '.($paramjs ? $paramjs : 'null').', '.$cover.', null, null, null, null, '.(is_numeric($time) ? $time : 'null').', null);';
	$extra = $extra ? '<script type="text/javascript" reload="1">'.$extra.'</script>' : '';
	if ($extrajs != '' && substr(trim($extrajs),0,7) != '<script'){
		$extrajs = '<script type="text/javascript" reload="1">'.$extrajs.'</script>';
	}
	$extra .= $extrajs;
	ob_end_clean();
	@header("Expires: -1");
	@header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);
	@header("Pragma: no-cache");
	@header("Content-type: text/xml; charset=".CHARSET);

	$string =  '<?xml version="1.0" encoding="'.CHARSET.'"?>'."\r\n";
	$string .= '<root><![CDATA['.$message.$extra.']]></root>';
	echo $string;exit;
}

/**
 * 20171012 kevin
 * 取上一步来源地址
 *
 * @param
 * @return string 字符串类型的返回结果
 */
function getReferer(){
    return str_replace(array('\'','"', '<', '>'), '', $_SERVER['HTTP_REFERER']);
}

/**
 * 输出信息
 *
 * @param string $msg 输出信息
 * @param string/array $url 跳转地址 当$url为数组时，结构为 array('msg'=>'跳转连接文字','url'=>'跳转连接');
 * @param string $show_type 输出格式 默认为html
 * @param string $msg_type 信息类型 succ 为成功，error为失败/错误
 * @param string $is_show  是否显示跳转链接，默认是为1，显示
 * @param int $time 跳转时间，默认为2秒
 * @return string 字符串类型的返回结果
 */
function showMessage($msg,$url='',$show_type='html',$msg_type='succ',$is_show=1,$time=2000){
    /**
     * 如果默认为空，则跳转至上一步链接
     */
    $url = ($url!='' ? $url : getReferer());

    $msg_type = in_array($msg_type,array('succ','error')) ? $msg_type : 'error';

    /**
     * 输出类型
     */
    switch ($show_type){
        case 'json':
            $return = '{';
            $return .= '"msg":"'.$msg.'",';
            $return .= '"url":"'.$url.'"';
            $return .= '}';
            echo $return;
            break;
        case 'exception':
            echo '<!DOCTYPE html>';
            echo '<html>';
            echo '<head>';
            echo '<meta http-equiv="Content-Type" content="text/html; charset='.CHARSET.'" />';
            echo '<title></title>';
            echo '<style type="text/css">';
            echo 'body { font-family: "Verdana";padding: 0; margin: 0;}';
            echo 'h2 { font-size: 12px; line-height: 30px; border-bottom: 1px dashed #CCC; padding-bottom: 8px;width:800px; margin: 20px 0 0 150px;}';
            echo 'dl { float: left; display: inline; clear: both; padding: 0; margin: 10px 20px 20px 150px;}';
            echo 'dt { font-size: 14px; font-weight: bold; line-height: 40px; color: #333; padding: 0; margin: 0; border-width: 0px;}';
            echo 'dd { font-size: 12px; line-height: 40px; color: #333; padding: 0px; margin:0;}';
            echo '</style>';
            echo '</head>';
            echo '<body>';
            echo '<h2>'.系统信息.'</h2>';
            echo '<dl>';
            echo '<dd>'.$msg.'</dd>';
            echo '<dt><p /></dt>';
            echo '<dd>'.系统运行出错，给您带来的访问不便，请联系客服寻求帮助.'</dd>';
            echo '<dd><p /><p /><p /><p /></dd>';
            echo '</dl>';
            echo '</body>';
            echo '</html>';
            exit;
            break;
        case 'javascript':
            echo "<script>";
            echo "alert('". $msg ."');";
            echo "location.href='". $url ."'";
            echo "</script>";
            exit;
            break;
        case 'tenpay':
            echo "<html><head>";
            echo "<meta name=\"TENCENT_ONLINE_PAYMENT\" content=\"China TENCENT\">";
            echo "<script language=\"javascript\">";
            echo "window.location.href='" . $url . "';";
            echo "</script>";
            echo "</head><body></body></html>";
            exit;
            break;
        default:
            echo "<script>";
            echo "alert('". $msg ."');";
            echo "location.href='". $url ."'";
            echo "</script>";
            exit;
            break;
            /**
             * 不显示右侧工具条
             */
            $this->assign('hidden_nctoolbar', 1);
            if (is_array($url)){
                foreach ($url as $k => $v){
                    $url[$k]['url'] = $v['url']?$v['url']:getReferer();
                }
            }
            /**
             * html输出形式
             * 指定为指定项目目录下的error模板文件
             */
            $this->assign('html_title','系統信息');
            $this->assign('msg',$msg);
            $this->assign('url',$url);
            $this->assign('msg_type',$msg_type);
            $this->assign('is_show',$is_show);
            $this->fetch('msg_layout');
    }
    exit;
}

/**
 * 字符串切割函数，一个字母算一个位置,一个字算2个位置
 *
 * @param string $string 待切割的字符串
 * @param int $length 切割长度
 * @param string $dot 尾缀
 */
function str_cut($string, $length, $dot = '')
{
	$string = str_replace(array('&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array(' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$maxi = $length - strlen($dot);
	$strcut = '';
	if(strtolower(CHARSET) == 'utf-8')
	{
		$n = $tn = $noc = 0;
		while($n < $strlen)
		{
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t < 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $maxi) break;
		}
		if($noc > $maxi) $n -= $tn;
		$strcut = substr($string, 0, $n);
	}
	else
	{
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen;
		for($i = 0; $i < $maxi; $i++)
		{
			$strcut .= ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
		}
	}
	$strcut = str_replace(array('&', '"', "'", '<', '>'), array('&amp;', '&quot;', '&#039;', '&lt;', '&gt;'), $strcut);
	return $strcut.$dot;
}


/**
 * 取得随机数
 *
 * @param int $length 生成随机数的长度
 * @param int $numeric 是否只产生数字随机数 1是0否
 * @return string
 */
function random($length, $numeric = 0) {
	$seed = base_convert(md5(microtime().$_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
	$seed = $numeric ? (str_replace('0', '', $seed).'012340567890') : ($seed.'zZ'.strtoupper($seed));
	$hash = '';
	$max = strlen($seed) - 1;
	for($i = 0; $i < $length; $i++) {
		$hash .= $seed{mt_rand(0, $max)};
	}
	return $hash;
}

if (!function_exists('array_under_reset')) {
    /**
     * 返回以原数组某个值为下标的新数据
     *
     * @param array $array
     * @param string $key
     * @param int $type 1一维数组2二维数组
     * @return array
     */
    function array_under_reset($array, $key, $type=1){
        if (is_array($array)){
            $tmp = array();
            foreach ($array as $v) {
                if ($type === 1){
                    $tmp[$v[$key]] = $v;
                }elseif($type === 2){
                    $tmp[$v[$key]][] = $v;
                }
            }
            return $tmp;
        }else{
            return $array;
        }
    }
}


define('ATTACH_WAYBILL','client/waybill');
define('ATTACH_COMMON','client/common');

define('SHOP_TEMPLATES_URL',get_root_url().'/static/client/default');

/**
 * 获取运单图片地址
 */
function getWaybillImageUrl($image_name = '') {
    if (is_file(ROOT_PATH . $image_name)) {
        return $image_name;
    } else {
        $image_path = '/' . ATTACH_WAYBILL . '/' . $image_name;
        if(is_file(BASE_UPLOAD_PATH . $image_path)) {
            return UPLOAD_SITE_URL . $image_path;
        }
    }
    return UPLOAD_SITE_URL.'/'.defaultGoodsImage('240');
}

/**
 * 20171012 kevin
 * 取得商品默认大小图片
 *
 * @param string $key	图片大小 small tiny
 * @return string
 */
function defaultGoodsImage($key){
    $file = str_ireplace('.', '_' . $key . '.', "default_goods_image.gif");
	return ATTACH_COMMON.'/'.$file;
}

/**
 * 获取物流详细信息
 */
function dfsockopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype  = 'URLENCODE', $allowcurl = TRUE) {
	return _dfsockopen($url, $limit, $post, $cookie, $bysocket, $ip, $timeout, $block, $encodetype, $allowcurl);
}

function _dfsockopen($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE, $encodetype  = 'URLENCODE', $allowcurl = TRUE) {
	$return = '';
	$matches = parse_url($url);
	$scheme = $matches['scheme'];
	$host = $matches['host'];
	$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
	$port = !empty($matches['port']) ? $matches['port'] : 80;

	if(function_exists('curl_init') && function_exists('curl_exec') && $allowcurl) {
		$ch = curl_init();
		$ip && curl_setopt($ch, CURLOPT_HTTPHEADER, array("Host: ".$host));
		curl_setopt($ch, CURLOPT_URL, $scheme.'://'.($ip ? $ip : $host).':'.$port.$path);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		if($post) {
			curl_setopt($ch, CURLOPT_POST, 1);
			if($encodetype == 'URLENCODE') {
				curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
			} else {
				parse_str($post, $postarray);
				curl_setopt($ch, CURLOPT_POSTFIELDS, $postarray);
			}
		}
		if($cookie) {
			curl_setopt($ch, CURLOPT_COOKIE, $cookie);
		}
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		$data = curl_exec($ch);
		$status = curl_getinfo($ch);
		$errno = curl_errno($ch);
		curl_close($ch);
		if($errno || $status['http_code'] != 200) {
			return;
		} else {
			return !$limit ? $data : substr($data, 0, $limit);
		}
	}

	if($post) {
		$out = "POST $path HTTP/1.0\r\n";
		$header = "Accept: */*\r\n";
		$header .= "Accept-Language: zh-cn\r\n";
		$boundary = $encodetype == 'URLENCODE' ? '' : '; boundary='.trim(substr(trim($post), 2, strpos(trim($post), "\n") - 2));
		$header .= $encodetype == 'URLENCODE' ? "Content-Type: application/x-www-form-urlencoded\r\n" : "Content-Type: multipart/form-data$boundary\r\n";
		$header .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$header .= "Host: $host:$port\r\n";
		$header .= 'Content-Length: '.strlen($post)."\r\n";
		$header .= "Connection: Close\r\n";
		$header .= "Cache-Control: no-cache\r\n";
		$header .= "Cookie: $cookie\r\n\r\n";
		$out .= $header.$post;
	} else {
		$out = "GET $path HTTP/1.0\r\n";
		$header = "Accept: */*\r\n";
		$header .= "Accept-Language: zh-cn\r\n";
		$header .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$header .= "Host: $host:$port\r\n";
		$header .= "Connection: Close\r\n";
		$header .= "Cookie: $cookie\r\n\r\n";
		$out .= $header;
	}

	$fpflag = 0;
	if(!$fp = @fsocketopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout)) {
		$context = array(
			'http' => array(
				'method' => $post ? 'POST' : 'GET',
				'header' => $header,
				'content' => $post,
				'timeout' => $timeout,
			),
		);
		$context = stream_context_create($context);
		$fp = @fopen($scheme.'://'.($ip ? $ip : $host).':'.$port.$path, 'b', false, $context);
		$fpflag = 1;
	}

	if(!$fp) {
		return '';
	} else {
		stream_set_blocking($fp, $block);
		stream_set_timeout($fp, $timeout);
		@fwrite($fp, $out);
		$status = stream_get_meta_data($fp);
		if(!$status['timed_out']) {
			while (!feof($fp) && !$fpflag) {
				if(($header = @fgets($fp)) && ($header == "\r\n" ||  $header == "\n")) {
					break;
				}
			}

			$stop = false;
			while(!feof($fp) && !$stop) {
				$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
				$return .= $data;
				if($limit) {
					$limit -= strlen($data);
					$stop = $limit <= 0;
				}
			}
		}
		@fclose($fp);
		return $return;
	}
}

function fsocketopen($hostname, $port = 80, &$errno, &$errstr, $timeout = 15) {
	$fp = '';
	if(function_exists('fsockopen')) {
		$fp = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
	} elseif(function_exists('pfsockopen')) {
		$fp = @pfsockopen($hostname, $port, $errno, $errstr, $timeout);
	} elseif(function_exists('stream_socket_client')) {
		$fp = @stream_socket_client($hostname.':'.$port, $errno, $errstr, $timeout);
	}
	return $fp;
}


/**
 * 根据 classuri获取后台spm值
 * @param string $classUri uri地址 格式为：/模型名称/控制器名称/方法名称
 * @param string $table 菜单表名 默认为system_menu 总后台菜单
 * @return string 返回格式为：m-123-456
 */
function get_spm_by_classuri($classUri, $table = 'client_menu') {
    $menu = Db::name($table)->where(['url' => strtolower($classUri)])->field('id, pid')->find();halt($menu);
    if($menu['pid']!=0){
    	$menu1=Db::name($table)->where(['id' => $menu['pid']])->field('id, pid')->find();
    }
    
    $spm = 'm-'.$menu1['pid'].'-'.$menu['id'];
    return $spm;
}

/**
 * 根据 classuri获取后台spm值
 * @param string $classUri uri地址 格式为：/模型名称/控制器名称/方法名称
 * @param string $table 菜单表名 默认为system_menu 总后台菜单
 * @return string 返回格式为：m-123-456
 */
function get_spm_by_classuri2($classUri, $table = 'client_menu') {
    $menu = Db::name($table)->where(['url' => strtolower($classUri)])->field('id, pid')->find();
    $spm = 'm-'.$menu['pid'].'-'.$menu['id'];
    return $spm;
}

/*前端 配置 ------kevin 20171218------------------------  */
/**
 * kevin 20171218
 * 文章显示位置状态,1默认系统前台,2买家,3卖家,4全站
 */
define('ARTICLE_POSIT_SHOP', 1);//1默认系统前台
define('ARTICLE_POSIT_BUYER', 2);//2买家
define('ARTICLE_POSIT_SELLER', 3);//3卖家
define('ARTICLE_POSIT_ALL', 4);//4全站


/**
 * 设置上传文件名
 *
 * @return string
 */
function set_filename()
{
    $filename = sprintf('%010d',time() - 946656000)
        . sprintf('%03d', microtime() * 1000)
        . sprintf('%04d', mt_rand(0,9999));

    return $filename;
}

/**
 * PHP限制新闻题目的显示字数,字数过多显示省略号
 */
/**
 * 字符串截取
 *
 */
function sub_str($str, $length = 0, $append = true)
{
    $str = trim($str);
    $strlength = strlen($str);
 
    if ($length == 0 || $length >= $strlength)
    {
        return $str;  //截取长度等于0或大于等于本字符串的长度，返回字符串本身
    }
    elseif ($length < 0)  //如果截取长度为负数
    {
        $length = $strlength + $length;//那么截取长度就等于字符串长度减去截取长度
        if ($length < 0)
        {
            $length = $strlength;//如果截取长度的绝对值大于字符串本身长度，则截取长度取字符串本身的长度
        }
    }
 
    if (function_exists('mb_substr'))
    {
        $newstr = mb_substr($str, 0, $length, "utf-8");
    }
    elseif (function_exists('iconv_substr'))
    {
        $newstr = iconv_substr($str, 0, $length, "utf-8");
    }
    else
    {
        //$newstr = trim_right(substr($str, 0, $length));
        $newstr = substr($str, 0, $length);
    }
 
    if ($append && $str != $newstr)
    {
        $newstr .= '...';
    }
 
    return $newstr;
}

function getRefUrl() {
    return urlencode('http://'.$_SERVER['HTTP_HOST'].request_uri());
}

/**
 * 获取url中  0模块名 1控制器 2方法名
 */
function getAct($m=1){
	$url=trim($_SERVER['REQUEST_URI'],'/');// seller/storegoodsadd/index.html
	$res=explode('/',$url);
	return $res[$m];
}

/**
 * 删除地址参数(把参数的值赋值为0)
 *
 * @param array $param
 */
function dropParam($param) {
	$get = input('param.');
    if (!empty($param)) {
        foreach ($param as $key => $val) {
            $get[$val] = 0;
        }
    }
    
	if($get['curpage']){
		//页码处理
		$curpage = $get['curpage'];
		unset($get['curpage']);
		return url(request()->module().'/'.request()->controller().'/'.request()->action(), $get).'?curpage='.$curpage;
	}else{
		return url(request()->module().'/'.request()->controller().'/'.request()->action(), $get);
	}
    
}


/**
 * 替换地址参数(替换参数值)
 *
 * @param array $param
 */
function replaceParam($param) {
	$get = input('param.');
    if (!empty($param)) {
        foreach ($param as $key => $val) {
            $get[$key] = $val;
        }
    }
    
	if($get['curpage']){
		//页码处理
		$curpage = $get['curpage'];
		unset($get['curpage']);
		return url(request()->module().'/'.request()->controller().'/'.request()->action(), $get).'?curpage='.$curpage;
	}else{
		return url(request()->module().'/'.request()->controller().'/'.request()->action(), $get);
	}
}


/**
 * 封装分页操作到函数，方便调用
 *
 * @param str $total_num  数据总数
 * @param str $each_num  	每页显示数量
 * @param str $now_page 	当前页
 * @return str 
 */
function FU_page($total_num=null, $each_num=24){
	if(!empty($total_num)){
		$page = new \lib\HomePage;
		
		$page->set('total_num', $total_num);
		$page->set('each_num', $each_num);
		
		$page->set('now_page', request()->param('curpage', 1));
		
		return  $page->show();
	}
	return null;
}



define('THEME_PATH','theme/default'); // 静态模板路径

/**
 * 调用显示模板
 *
 * @param string $page_name        	
 * @param string $layout    
 * @param array $data   显示的数据  	
 * @param int $time        	
 */
function showPageHtml($page_name = '', $datas = array(), $layout = '', $time = 2000) {
	$tpl_file = THEME_PATH . '/' . $page_name . '.html';
	if (file_exists ($tpl_file)) {
		@header ( "Content-type: text/html; charset=UTF-8" );
		include_once($tpl_file);
	}
}


define('ATTACH_MALBUM','home/member');

/**
 * 取得买家缩略图的完整URL路径
 *
 * @param string $imgurl 商品名称
 * @param string $type 缩略图类型  值为240,1024
 * @return string
 */
function snsThumb($image_name = '', $type = ''){
    if (!in_array($type, array('240','1024'))) $type = '240';
    if (empty($image_name)){
        return UPLOAD_SITE_URL.'/'.defaultGoodsImage('240');
    }

    if(strpos($image_name, '/')) {
        $image = explode('/', $image_name);
        $image = end($image);
    } else {
        $image = $image_name;
    }

    list($member_id) = explode('_', $image);
    $file_path = 'home/member/'.$member_id.'/'.str_ireplace('.', '_'.$type.'.', $image_name);
    if(!file_exists(BASE_UPLOAD_PATH.'/'.$file_path)) {
        return UPLOAD_SITE_URL.'/'.defaultGoodsImage('240');
    }
    return UPLOAD_SITE_URL.'/'.$file_path;
}


/**
 * 20171012 kevin
 * 取得商品缩略图的完整URL路径，接收商品信息数组，返回所需的商品缩略图的完整URL
 *
 * @param array $goods 商品信息数组
 * @param string $type 缩略图类型  值为60,240,360,1280
 * @return string
 */
function thumb($goods = array(), $type = ''){
    $type_array = explode(',_', ltrim(GOODS_IMAGES_EXT, '_'));
    if (!in_array($type, $type_array)) {
        $type = '240';
    }
    if (empty($goods)){
        return UPLOAD_SITE_URL.'/'.defaultGoodsImage($type);
    }
    if (array_key_exists('apic_cover', $goods)) {
        $goods['goods_image'] = $goods['apic_cover'];
    }
    if (empty($goods['goods_image'])) {
        return UPLOAD_SITE_URL.'/'.defaultGoodsImage($type);
    }
    $search_array = explode(',', GOODS_IMAGES_EXT);
    $file = str_ireplace($search_array,'',$goods['goods_image']);
    $fname = basename($file);
    //取店铺ID
    if (preg_match('/^(\d+_)/',$fname)){
        $store_id = substr($fname,0,strpos($fname,'_'));
    }else{
        $store_id = $goods['store_id'];
    }

    if (!sysconf('oss.open')) {
        $file = $type == '' ? $file : str_ireplace('.', '_' . $type . '.', $file);
        if (!file_exists(BASE_UPLOAD_PATH.'/'.ATTACH_GOODS.'/'.$store_id.'/'.$file)){
            return UPLOAD_SITE_URL.'/'.defaultGoodsImage($type);
        }
        $thumb_host = UPLOAD_SITE_URL.'/'.ATTACH_GOODS;
        return $thumb_host.'/'.$store_id.'/'.$file;        
    } else {
        return sysconf('oss.img_url'). '/' . ATTACH_GOODS . '/' . $store_id . '/' . $file . '@!product-' . $type;
    }
}

/**
 * 商品图片
 */
define('GOODS_IMAGES_WIDTH', '60,240,360,1280');
define('GOODS_IMAGES_HEIGHT', '60,240,360,12800');
define('GOODS_IMAGES_EXT', '_60,_240,_360,_1280');
define('ATTACH_GOODS','shop/store/goods');
/**
 * 取得商品缩略图的完整URL路径，接收图片名称与店铺ID
 *
 * @param string $file 图片名称
 * @param string $type 缩略图尺寸类型，值为60,240,360,1280
 * @param mixed $store_id 店铺ID 如果传入，则返回图片完整URL,如果为假，返回系统默认图
 * @return string
 */
function cthumb($file, $type = '', $store_id = false) {
    $type_array = explode(',_', ltrim(GOODS_IMAGES_EXT, '_'));
    if (!in_array($type, $type_array)) {
        $type = '240';
    }
    if (empty($file)) {
        return UPLOAD_SITE_URL . '/' . defaultGoodsImage ( $type );
    }
    $search_array = explode(',', GOODS_IMAGES_EXT);
    $file = str_ireplace($search_array,'',$file);
    $fname = basename($file);
    // 取店铺ID
    if ($store_id === false || !is_numeric($store_id)) {
        $store_id = substr ( $fname, 0, strpos ( $fname, '_' ) );
    }
    if (!sysconf('oss.open')) {
        // 本地存储时，增加判断文件是否存在，用默认图代替
        if ( !file_exists(BASE_UPLOAD_PATH . '/' . ATTACH_GOODS . '/' . $store_id . '/' . ($type == '' ? $file : str_ireplace('.', '_' . $type . '.', $file)) )) {
            return UPLOAD_SITE_URL.'/'.defaultGoodsImage($type);
        }
        $thumb_host = UPLOAD_SITE_URL . '/' . ATTACH_GOODS;
        return $thumb_host . '/' . $store_id . '/' . ($type == '' ? $file : str_ireplace('.', '_' . $type . '.', $file));        
    } else {
        return sysconf('oss.img_url'). '/' . ATTACH_GOODS . '/' . $store_id . '/' . $file . '@!product-' . $type;
    }

}


/**
 * 通知邮件/通知消息 内容转换函数
 *
 * @param string $message 内容模板
 * @param array $param 内容参数数组
 * @return string 通知内容
 */
function ncReplaceText($message,$param){
    if(!is_array($param))return false;
    foreach ($param as $k=>$v){
        $message	= str_replace('{$'.$k.'}',$v,$message);
    }
    return $message;
}

/**
* 验证手机号是否正确
* @author 
* @param number $mobile
*/
function isMobile($mobile) {
    if (!is_numeric($mobile)) {
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}

/**
 * 取得结算文字输出形式 goods
 *
 * @param array $bill_state
 * @return string 描述输出
 */
function billState($bill_state) {
    return str_replace(
        array('1','2','3','4'),
        array('已出账','商家已确认','平台已审核','结算完成'),
        $bill_state);
}


//以下是定义结算单状态
//默认
define('BILL_STATE_CREATE',1);
//店铺已确认
define('BILL_STATE_STORE_COFIRM',2);
//平台已审核
define('BILL_STATE_SYSTEM_CHECK',3);
//结算完成
define('BILL_STATE_SUCCESS',4);


define('nc_store_auto_share_new1','亲，我家又上新宝贝了。');
define('nc_store_auto_share_new2','亲，为您推荐一款本店新上宝贝。');
define('nc_store_auto_share_new3','亲，我家又上新宝贝了！快来逛逛看更多吧。');
define('nc_store_auto_share_new4','亲，我家又上新宝贝了。');
define('nc_store_auto_share_new5','亲，为您推荐一款本店新上宝贝。');

define('nc_store_auto_share_xianshi1','限时折扣，玩得就是心跳。');
define('nc_store_auto_share_xianshi2','省心又省钱，活动促销中。');
define('nc_store_auto_share_xianshi3','只买对的，不买贵的，宝贝限时折扣中。');
define('nc_store_auto_share_xianshi4','宝贝限时折扣中，性价比超高哟。');
define('nc_store_auto_share_xianshi5','折扣限时，不买不死心哇~');

define('nc_store_auto_share_mansong1','满即送，快行动！');
define('nc_store_auto_share_mansong2','不满不送，不送不买~');
define('nc_store_auto_share_mansong3','满啦就送啦，快快行动吧~');
define('nc_store_auto_share_mansong4','我家有满就送活动啦，亲快去查看下详情吧');
define('nc_store_auto_share_mansong5','我家有满就送活动啦，亲快去查看下详情吧');

define('nc_store_auto_share_bundling1','搭配购买更省钱');
define('nc_store_auto_share_bundling2','搭配的是品质，捡到的是实惠！');
define('nc_store_auto_share_bundling3','搭配不错，省心省钱更不会错');
define('nc_store_auto_share_bundling4','省心又省钱，找套餐就对了！');
define('nc_store_auto_share_bundling5','省心又省钱，套餐促销中～');

define('nc_store_auto_share_groupbuy1','打折的是价格，不打折的是品格！');
define('nc_store_auto_share_groupbuy2','抢购进万家，实惠你我他。');
define('nc_store_auto_share_groupbuy3','今天您团了吗？还没有？快来参加吧！');
define('nc_store_auto_share_groupbuy4','让您足不出户，便宜到家，快来抢购吧！');
define('nc_store_auto_share_groupbuy5','品质与价格的双优选择，快来看看吧。');


/**
 * 获取当前域名
 */
function FU_current_domain(){
	return request()->domain();
}

/**
 * 获取当前入口文件
 */
function FU_current_file(){
	return request()->baseFile();
}

/**
 * 获取包含域名的完整URL地址
 */
function FU_current_url(){
	return request()->url(true);
}

/**
 * 获取URL访问的ROOT地址
 */
function FU_current_root(){
	return request()->root(true);
}

/**
 * 获取当前模块名称
 */
function FU_current_module(){
	return request()->module();
}

/**
 * 获取当前控制器名称
 */
function FU_current_controller(){
	return request()->controller();
}

/**
 * 获取当前操作名称
 */
function FU_current_action(){
	return request()->action();
}


/**
 * 获得折线图统计图数据
 * param $statarr 图表需要的设置项
 */
function getStatData_LineLabels($stat_arr){
	//图表区、图形区和通用图表配置选项
	$stat_arr['chart']['type'] = 'line';
	//图表序列颜色数组
	$stat_arr['colors']?'':$stat_arr['colors'] = array('#058DC7', '#ED561B', '#8bbc21', '#0d233a');
	//去除版权信息
	$stat_arr['credits']['enabled'] = false;
	//导出功能选项
	$stat_arr['exporting']['enabled'] = false;
	//标题如果为字符串则使用默认样式
	is_string($stat_arr['title'])?$stat_arr['title'] = array('text'=>"<b>{$stat_arr['title']}</b>",'x'=>-20):'';
	//子标题如果为字符串则使用默认样式
	is_string($stat_arr['subtitle'])?$stat_arr['subtitle'] = array('text'=>"<b>{$stat_arr['subtitle']}</b>",'x'=>-20):'';
	//Y轴如果为字符串则使用默认样式
	if(is_string($stat_arr['yAxis'])){
		$text = $stat_arr['yAxis'];
		unset($stat_arr['yAxis']);
		$stat_arr['yAxis']['title']['text'] = $text;
	}
	return json_encode($stat_arr);
}

/**
 * 获得Column2D统计图数据
 */
function getStatData_Column2D($stat_arr){
    //图表区、图形区和通用图表配置选项
	$stat_arr['chart']['type'] = 'column';
	//去除版权信息
	$stat_arr['credits']['enabled'] = false;
	//导出功能选项
	$stat_arr['exporting']['enabled'] = false;
	//标题如果为字符串则使用默认样式
	is_string($stat_arr['title'])?$stat_arr['title'] = array('text'=>"<b>{$stat_arr['title']}</b>",'x'=>-20):'';
	//子标题如果为字符串则使用默认样式
	is_string($stat_arr['subtitle'])?$stat_arr['subtitle'] = array('text'=>"<b>{$stat_arr['subtitle']}</b>",'x'=>-20):'';
	//Y轴如果为字符串则使用默认样式
	if(is_string($stat_arr['yAxis'])){
		$text = $stat_arr['yAxis'];
		unset($stat_arr['yAxis']);
		$stat_arr['yAxis']['title']['text'] = $text;
	}
	//柱形的颜色数组
	$color = array('#7a96a4','#cba952','#667b16','#a26642','#349898','#c04f51','#5c315e','#445a2b','#adae50','#14638a','#b56367','#a399bb','#070dfa','#47ff07','#f809b7');
	
	foreach ($stat_arr['series'] as $series_k=>$series_v){
	    foreach ($series_v['data'] as $data_k=>$data_v){
	        $data_v['color'] = $color[$data_k];
	        $series_v['data'][$data_k] = $data_v;
	    }
	    $stat_arr['series'][$series_k]['data'] = $series_v['data'];
	}
	//print_r($stat_arr); die;
	return json_encode($stat_arr);
}

/**
 * 获得Basicbar统计图数据
 */
function getStatData_Basicbar($stat_arr){
    //图表区、图形区和通用图表配置选项
	$stat_arr['chart']['type'] = 'bar';
	//去除版权信息
	$stat_arr['credits']['enabled'] = false;
	//导出功能选项
	$stat_arr['exporting']['enabled'] = false;
	//显示datalabel
	$stat_arr['plotOptions']['bar']['dataLabels']['enabled'] = true;
	//标题如果为字符串则使用默认样式
	is_string($stat_arr['title'])?$stat_arr['title'] = array('text'=>"<b>{$stat_arr['title']}</b>",'x'=>-20):'';
	//子标题如果为字符串则使用默认样式
	is_string($stat_arr['subtitle'])?$stat_arr['subtitle'] = array('text'=>"<b>{$stat_arr['subtitle']}</b>",'x'=>-20):'';
	//Y轴如果为字符串则使用默认样式
	if(is_string($stat_arr['yAxis'])){
		$text = $stat_arr['yAxis'];
		unset($stat_arr['yAxis']);
		$stat_arr['yAxis']['title']['text'] = $text;
	}
	//柱形的颜色数组
	$color = array('#7a96a4','#cba952','#667b16','#a26642','#349898','#c04f51','#5c315e','#445a2b','#adae50','#14638a','#b56367','#a399bb','#070dfa','#47ff07','#f809b7');
	
	foreach ($stat_arr['series'] as $series_k=>$series_v){
	    foreach ($series_v['data'] as $data_k=>$data_v){
	        if (!$data_v['color']){
	            $data_v['color'] = $color[$data_k%15];
	        }
	        $series_v['data'][$data_k] = $data_v;
	    }
	    $stat_arr['series'][$series_k]['data'] = $series_v['data'];
	}
	//print_r($stat_arr); die;
	return json_encode($stat_arr);
}

/**
 * 计算环比
 */
function getHb($updata, $currentdata){
	if($updata != 0){
		$mtomrate = round(($currentdata - $updata)/$updata*100, 2).'%';
	} else {
	    $mtomrate = '-';
	}
	return $mtomrate; 
}

/**
 * 计算同比
 */
function getTb($updata, $currentdata){
	if($updata != 0){
		$ytoyrate = round(($currentdata - $updata)/$updata*100, 2).'%';
	} else {
	    $ytoyrate = '-';
	}
	return $ytoyrate; 
}

/**
 * 地图统计图
 */
function getStatData_Map($stat_arr){
    //$color_arr = array('#f63a3a','#ff5858','#ff9191','#ffc3c3','#ffd5d5');
    $color_arr = array('#fd0b07','#ff9191','#f7ba17','#fef406','#25aae2');
    $stat_arrnew = array();
    foreach ($stat_arr as $k=>$v){
        $stat_arrnew[] = array('cha'=>$v['cha'],'name'=>$v['name'],'des'=>$v['des'],'color'=>$color_arr[$v['level']]);
    }
    return json_encode($stat_arrnew);
}
/**
 * 获得饼形图数据
 */
function getStatData_Pie($data){
	$stat_arr['chart']['type'] = 'pie';
	$stat_arr['credits']['enabled'] = false;
	$stat_arr['title']['text'] = $data['title'];
	$stat_arr['tooltip']['pointFormat'] = '{series.name}: <b>{point.y}</b>';
	$stat_arr['plotOptions']['pie'] = array(
		'allowPointSelect'=>true,
		'cursor'=>'pointer',
		'dataLabels'=>array(
			'enabled'=>$data['label_show'],
			'color'=>'#000000',
			'connectorColor'=>'#000000',
			'format'=>'<b>{point.name}</b>: {point.percentage:.1f} %'
		)
	);
	$stat_arr['series'][0]['name'] = $data['name'];
	$stat_arr['series'][0]['data'] = array();
	foreach ($data['series'] as $k=>$v){
		$stat_arr['series'][0]['data'][] = array($v['p_name'],$v['allnum']);
	}
	//exit(json_encode($stat_arr));
	return json_encode($stat_arr);
}


/**
 * 时间框架

 */

/**
 * 获得系统年份数组
 */
function getSystemYearArr(){
    $year_arr = array('2010'=>'2010','2011'=>'2011','2012'=>'2012','2013'=>'2013','2014'=>'2014','2015'=>'2015','2016'=>'2016','2017'=>'2017','2018'=>'2018','2019'=>'2019','2020'=>'2020');
    return $year_arr;
}
/**
 * 获得系统月份数组
 */
function getSystemMonthArr(){
	$month_arr = array('1'=>'01','2'=>'02','3'=>'03','4'=>'04','5'=>'05','6'=>'06','7'=>'07','8'=>'08','9'=>'09','10'=>'10','11'=>'11','12'=>'12');
	return $month_arr;
}
/**
 * 获得系统周数组
 */
function getSystemWeekArr(){
	$week_arr = array('1'=>'周一','2'=>'周二','3'=>'周三','4'=>'周四','5'=>'周五','6'=>'周六','7'=>'周日');
	return $week_arr;
}
/**
 * 获取某月的最后一天
 */
function getMonthLastDay($year, $month){
    $t = mktime(0, 0, 0, $month + 1, 1, $year);
    $t = $t - 60 * 60 * 24;
    return $t;
}
/**
 * 获得系统某月的周数组，第一周不足的需要补足
 */
function getMonthWeekArr($current_year, $current_month){
    //该月第一天
    $firstday = strtotime($current_year.'-'.$current_month.'-01');
    //该月的第一周有几天
    $firstweekday = (7 - date('N',$firstday) +1);
    //计算该月第一个周一的时间
    $starttime = $firstday-3600*24*(7-$firstweekday);
    //该月的最后一天
    $lastday = strtotime($current_year.'-'.$current_month.'-01'." +1 month -1 day");
    //该月的最后一周有几天
    $lastweekday = date('N',$lastday);
    //该月的最后一个周末的时间
    $endtime = $lastday-3600*24*($lastweekday%7);
    $step = 3600*24*7;//步长值
    $week_arr = array();
    for ($i=$starttime; $i<$endtime; $i= $i+3600*24*7){
        $week_arr[] = array('key'=>date('Y-m-d',$i).'|'.date('Y-m-d',$i+3600*24*6), 'val'=>date('Y-m-d',$i).'~'.date('Y-m-d',$i+3600*24*6));
    }
    return $week_arr;
}
/**
 * 获取本周的开始时间和结束时间
 */
function getWeek_SdateAndEdate($current_time){
    $current_time = strtotime(date('Y-m-d',$current_time));
	$return_arr['sdate'] = date('Y-m-d', $current_time-86400*(date('N',$current_time) - 1));
	$return_arr['edate'] = date('Y-m-d', $current_time+86400*(7- date('N',$current_time)));
	return $return_arr;
}


/**
 * KV缓存 读
 *
 * @param string $key 缓存名称
 * @param boolean $callback 缓存读取失败时是否使用回调 true代表使用cache.model中预定义的缓存项 默认不使用回调
 * @param callable $callback 传递非boolean值时 通过is_callable进行判断 失败抛出异常 成功则将$key作为参数进行回调
 * @return mixed
 */
use \service\Cache;
if (!function_exists('rkcache')) {
    function rkcache($key, $callback = false)
    {
        $cacher = new \think\Cache();

        $value = $cacher->get($key);
        if ($value === false && $callback !== false) {

            if ($callback === true) {
                $callback = array(model('cache'), 'call');
            }

            if (!is_callable($callback)) {
                throw new Exception('Invalid rkcache callback!');
            }

            $value = call_user_func($callback, $key);
            wkcache($key, $value);
        }

        return $value;
    }
}

if (!function_exists('wkcache')) {
    /**
     * KV缓存 写
     *
     * @param string $key 缓存名称
     * @param mixed $value 缓存数据 若设为否 则下次读取该缓存时会触发回调（如果有）
     * @param int $expire 缓存时间 单位秒 null代表不过期
     * @return boolean
     */
    function wkcache($key, $value, $expire = null)
    {

        $cacher = new \think\Cache();

        return $cacher->set($key, $value, null, $expire);
    }
}

if (!function_exists('showMessage')) {
    /**
     * 输出信息
     *
     * @param string $msg 输出信息
     * @param string/array $url 跳转地址 当$url为数组时，结构为 array('msg'=>'跳转连接文字','url'=>'跳转连接');
     * @param string $show_type 输出格式 默认为html
     * @param string $msg_type 信息类型 succ 为成功，error为失败/错误
     * @param string $is_show  是否显示跳转链接，默认是为1，显示
     * @param int $time 跳转时间，默认为2秒
     * @return string 字符串类型的返回结果
     */
    function showMessage($msg,$url='',$show_type='html',$msg_type='succ',$is_show=1,$time=2000){
        /**
         * 如果默认为空，则跳转至上一步链接
         */
        $url = ($url!='' ? $url : getReferer());

        $msg_type = in_array($msg_type,array('succ','error')) ? $msg_type : 'error';

        /**
         * 输出类型
         */
        switch ($show_type){
            case 'json':
                $return = '{';
                $return .= '"msg":"'.$msg.'",';
                $return .= '"url":"'.$url.'"';
                $return .= '}';
                echo $return;
                break;
            case 'exception':
                echo '<!DOCTYPE html>';
                echo '<html>';
                echo '<head>';
                echo '<meta http-equiv="Content-Type" content="text/html; charset='.CHARSET.'" />';
                echo '<title></title>';
                echo '<style type="text/css">';
                echo 'body { font-family: "Verdana";padding: 0; margin: 0;}';
                echo 'h2 { font-size: 12px; line-height: 30px; border-bottom: 1px dashed #CCC; padding-bottom: 8px;width:800px; margin: 20px 0 0 150px;}';
                echo 'dl { float: left; display: inline; clear: both; padding: 0; margin: 10px 20px 20px 150px;}';
                echo 'dt { font-size: 14px; font-weight: bold; line-height: 40px; color: #333; padding: 0; margin: 0; border-width: 0px;}';
                echo 'dd { font-size: 12px; line-height: 40px; color: #333; padding: 0px; margin:0;}';
                echo '</style>';
                echo '</head>';
                echo '<body>';
                echo '<h2>'.系统信息.'</h2>';
                echo '<dl>';
                echo '<dd>'.$msg.'</dd>';
                echo '<dt><p /></dt>';
                echo '<dd>'.系统运行出错，给您带来的访问不便，请联系客服寻求帮助.'</dd>';
                echo '<dd><p /><p /><p /><p /></dd>';
                echo '</dl>';
                echo '</body>';
                echo '</html>';
                exit;
                break;
            case 'javascript':
                echo "<script>";
                echo "alert('". $msg ."');";
                echo "location.href='". $url ."'";
                echo "</script>";
                exit;
                break;
            case 'tenpay':
                echo "<html><head>";
                echo "<meta name=\"TENCENT_ONLINE_PAYMENT\" content=\"China TENCENT\">";
                echo "<script language=\"javascript\">";
                echo "window.location.href='" . $url . "';";
                echo "</script>";
                echo "</head><body></body></html>";
                exit;
                break;
            default:
                echo "<script>";
                echo "alert('". $msg ."');";
                echo "location.href='". $url ."'";
                echo "</script>";
                exit;
                break;
                /**
                 * 不显示右侧工具条
                 */
                $this->assign('hidden_nctoolbar', 1);
                if (is_array($url)){
                    foreach ($url as $k => $v){
                        $url[$k]['url'] = $v['url']?$v['url']:getReferer();
                    }
                }
                /**
                 * html输出形式
                 * 指定为指定项目目录下的error模板文件
                 */
                $this->assign('html_title','系統信息');
                $this->assign('msg',$msg);
                $this->assign('url',$url);
                $this->assign('msg_type',$msg_type);
                $this->assign('is_show',$is_show);
                $this->fetch('msg_layout');
        }
        exit;
    }
}

if (!function_exists('dis_number')) {
    //手机号码+身份证安全隐藏
    function dis_number($arr){
        // return $arr;
        switch (strlen($arr)) {
            case 11:
                return substr($arr,0,3).'****'.substr($arr,-4);
                break;
            
            default:
                return substr($arr,0,6).'**************';
                break;
        }
    }
}
